package com.taiji.dianthus.service.sys.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.dao.sys.OrgRepository;
import com.taiji.dianthus.dao.sys.UserRepository;
import com.taiji.dianthus.domain.sys.DSysOrg;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.service.sys.OrgService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PushOrgServiceImpl
 * @Description
 * @Author H.M
 * @Date 2020/1/7
 */
@Service("pushOrg")
@Transactional(rollbackFor = Exception.class)
public class OrgServiceImpl implements OrgService {

    Log log = LogFactory.getLog(OrgServiceImpl.class);
    @Autowired
    private OrgRepository orgRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 查询组织列表
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public BusinessMessage list(Integer currentPage, Integer pageSize) {
        BusinessMessage message = new BusinessMessage();
        try {
            //排序
            List<Sort.Order> orders = new ArrayList<>();
            orders.add(new Sort.Order(Sort.Direction.ASC, "orgOrder"));
            orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
            //分页参数
            Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by(orders));
            Page<DSysOrg> orgPage;
            Specification<DSysOrg> spec = (Root<DSysOrg> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                List<Predicate> pl = new ArrayList<Predicate>();
                // 查询出未删除的
                pl.add(cb.equal(root.<Integer>get("enableFlag"), 1));
                return cb.and(pl.toArray(new Predicate[0]));
            };
            orgPage = orgRepository.findAll(spec, pageable);
            message.setData(orgPage);
            message.setSuccess(true);
            message.setMsg("查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("查询失败");

        }
        return message;
    }

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @Override
    public DSysOrg getOrgById(String id) {
        return orgRepository.getById(id);
    }

    @Override
    public String getOrgNameById(String id) {
        DSysOrg pushOrg = orgRepository.getById(id);
        if (null == pushOrg) {
            return "-";
        } else {
            return pushOrg.getOrgName();
        }
    }

    /**
     * 查询所有列表
     *
     * @return
     */
    @Override
    public List<DSysOrg> listAll() {
        return orgRepository.listAll();
    }

    /**
     * 根据id数组查询集合
     *
     * @param ids
     * @return
     */
    @Override
    public List<DSysOrg> listByIds(String[] ids) {
        return orgRepository.listByIdArray(ids);
    }

    /**
     * 查询所有除参数外列表
     *
     * @param orgId
     * @return
     */
    @Override
    public List<DSysOrg> listAllExclusionId(String orgId) {
        return orgRepository.listAllExclusionId(orgId);
    }

    /**
     * 根据ID集合查询
     *
     * @param ids
     * @return
     */
    @Override
    public List<DSysOrg> listByIds(List<String> ids) {
        return orgRepository.listByIdList(ids);
    }

    /**
     * 获取组织树的json数据
     *
     * @return
     */
    @Override
    public JSONArray getAllOrgTree() {
        //获取全部组织信息
        List<DSysOrg> dSysOrgs = orgRepository.listAll();
        //设置同步组织树数据
        JSONArray jsonArray = new JSONArray();
        for (DSysOrg sysOrg : dSysOrgs) {
            JSONObject json = new JSONObject();
            if (StringUtils.isEmpty(sysOrg.getParentId())) {
                json.put("pId", null);
                json.put("isParent", true);
            } else {
                json.put("pId", sysOrg.getParentId());
            }
            json.put("name", sysOrg.getOrgName());
            json.put("id", sysOrg.getId());
            if (null != sysOrg.getOrgLevel() && sysOrg.getOrgLevel() <= 1) {
                json.put("open", true);
            }
            jsonArray.add(json);
        }
        return jsonArray;
    }

    /**
     * 查询所有在用组织
     *
     * @return
     */
    @Override
    public Integer countOrg() {
        return orgRepository.countOrg();
    }

    /**
     * 保存方法
     *
     * @param pushOrg
     * @return
     */
    @Override
    public BusinessMessage save(DSysOrg pushOrg) {
        BusinessMessage message = new BusinessMessage();
        try {
            orgRepository.save(pushOrg);
            message.setMsg("保存成功");
            message.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("保存失败");
        }
        return message;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public BusinessMessage delete(String id) {
        BusinessMessage message = new BusinessMessage();
        try {
            //查询是否有用户存在
            Integer count = userRepository.countByOrgId(id);
            if (count > 0) {
                message.setMsg("删除失败，该组织下还有用户");
                return message;
            }
            Integer child = orgRepository.countByParentId(id);
            if (child > 0) {
                message.setMsg("删除失败，该组织下还有子组织");
                return message;
            }
            orgRepository.updateFlag(id);
            message.setMsg("删除成功");
            message.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("删除失败，系统错误");
        }

        return message;
    }

    @Override
    public JSONArray getOrgUserTree() {
        //获取全部组织信息
        List<DSysOrg> dSysOrgs = orgRepository.listAll();
        //查询所有有组织机构的用户数据
        List<DSysUser> allUserList = userRepository.listUserWithOrg();
        //设置同步用户树 组织数据
        JSONArray jsonArray = new JSONArray();
        for (DSysOrg sysOrg : dSysOrgs) {
            JSONObject json = new JSONObject();
            if (StringUtils.isEmpty(sysOrg.getParentId())) {
                json.put("pId", null);
                json.put("isParent", true);
            } else {
                json.put("pId", sysOrg.getParentId());
            }
            json.put("id", sysOrg.getId());
            json.put("name", sysOrg.getOrgName());
            json.put("open", false);
            jsonArray.add(json);
        }
        //设置同步用户树 用户数据  同步用户比对
        for (DSysUser dSysUser : allUserList) {
            JSONObject json = new JSONObject();
            json.put("pId", dSysUser.getOrgId());
            json.put("id", dSysUser.getId());
            json.put("name", dSysUser.getName());
            json.put("loginName", dSysUser.getUserLoginName());
            json.put("type", "user");
            json.put("userPhone", dSysUser.getUserPhone());
            json.put("open", false);
            jsonArray.add(json);
        }
        return jsonArray;
    }

    @Override
    public DSysOrg getOrgByPushId(String orgId) {
        return orgRepository.getByPushId(orgId);
    }

    @Override
    public Integer getOrgByOrgName(String orgName, String parentId) {
        return orgRepository.getOrgByOrgName(orgName, parentId);
    }

    @Override
    public List<DSysOrg> getZijiOrg(String id) {
        return orgRepository.getZijiOrg(id);
    }

    @Override
    public Integer getOrgOrgNameByParentNull(String orgName) {
        return orgRepository.getOrgOrgNameByParentNull(orgName);
    }

    @Override
    public Integer editOrgByOrgName(String orgName, String parentId, String editId) {
        return orgRepository.editOrgByOrgName(orgName, parentId, editId);
    }

    @Override
    public Integer editOrgOrgNameByParentNull(String orgName, String editId) {
        return orgRepository.editOrgOrgNameByParentNull(orgName, editId);
    }

    @Override
    public List<BusinessMessage> addSynBaseOrg(String jsonArrayStr) {
        log.info("---------------调用新增组织方法 START ---------------------");
        List<BusinessMessage> messageList = new ArrayList<>();
        try {
            jsonArrayStr = new String(jsonArrayStr.getBytes("UTF-8"), "UTF-8");
            List<Map<String, Object>> mapList = JSONArray.parseObject(jsonArrayStr, List.class);
            if (null != mapList && mapList.size() > 0) {
                for (Map<String, Object> map : mapList) {
                    log.info("******************* 组织新增信息 START*********************");
                    String pushId = (String) map.get("id");
                    String orgName = (String) map.get("orgName");
                    String parentId = (String) map.get("parentId");
                    DSysOrg orgByPushId = orgRepository.getByPushId(pushId);//当前部门信息
                    DSysOrg orgByParentId = null;
                    DSysOrg org = new DSysOrg();
                    BusinessMessage message = new BusinessMessage();
                    if (orgByPushId != null) {
                        message.setCode("101");
                        message.setMsg("添加重复组织");
                        message.setData(pushId);
                        messageList.add(message);
                    }
                    if (!StringUtils.isEmpty(parentId) && !"".equals(parentId)) {
                        orgByParentId = orgRepository.getByPushId(parentId);//上级部门信息
                        if (orgByParentId == null) {
                            message.setCode("102");
                            message.setMsg("增加组织的上级节点不存在");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                        Integer count = orgRepository.getOrgByOrgName(orgName, orgByParentId.getId());
                        if (count > 0) {
                            message.setCode("101");
                            message.setMsg("增加组织时同级组织名称重复");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                        org.setParentId(orgByParentId.getId());
                    } else {
                        Integer orgByOrgName = orgRepository.getOrgOrgNameByParentNull(orgName);
                        if (orgByOrgName > 0) {
                            message.setCode("101");
                            message.setMsg("增加组织时同级组织名称重复");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                    }
                    org.setPushId(pushId);
                    org.setEnableFlag((Integer) map.get("enableFlag"));
                    org.setOrgAddress((String) map.get("orgAddress"));
                    org.setOrgCode((String) map.get("orgCode"));
                    org.setOrgLevel((Integer) map.get("orgLevel"));
                    org.setOrgName(orgName);
                    org.setOrgOrder((Integer) map.get("orgOrder"));
                    org.setOrgPhone((String) map.get("orgPhone"));
                    orgRepository.save(org);
                    log.info("******************* 组织新增信息 END*********************");
                }
            } else {
                BusinessMessage message = new BusinessMessage();
                message.setCode("1003");
                message.setMsg("推送的数据为空");
                messageList.add(message);
            }
        } catch (Exception e) {
            BusinessMessage message = new BusinessMessage();
            e.printStackTrace();
            message.setCode("1002");
            message.setMsg("组织新增失败，系统异常");
            messageList.add(message);
        } finally {
            log.info("---------------调用新增组织方法 END ---------------------");
            return messageList;
        }
    }

    @Override
    public List<BusinessMessage> updateSynBaseOrg(String jsonArrayStr) {
        log.info("---------------调用更新组织方法 START ---------------------");
        List<BusinessMessage> messageList = new ArrayList<>();
        try {
            jsonArrayStr = new String(jsonArrayStr.getBytes("UTF-8"), "UTF-8");
            List<Map<String, Object>> mapList = JSONArray.parseObject(jsonArrayStr, List.class);
            if (null != mapList && mapList.size() > 0) {
                for (Map<String, Object> map : mapList) {
                    log.info("***********更新组织信息 START****************");
                    String pushId = (String) map.get("id");
                    String orgName = (String) map.get("orgName");
                    String parentId = (String) map.get("parentId");
                    DSysOrg orgByPushId = orgRepository.getByPushId(pushId);
                    BusinessMessage message = new BusinessMessage();
                    if (orgByPushId == null) {
                        message.setCode("301");
                        message.setMsg("修改组织的不存在");
                        message.setData(pushId);
                        messageList.add(message);
                    }
                    DSysOrg orgByParentId = null;
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(parentId) && !"".equals(parentId)) {
                        orgByParentId = orgRepository.getByPushId(parentId);
                        if (orgByParentId == null) {
                            message.setCode("302");
                            message.setMsg("修改组织的上级节点不存在");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                        Integer count = orgRepository.editOrgByOrgName(orgName, orgByParentId.getId(), orgByPushId.getId());
                        if (count > 0) {
                            message.setCode("303");
                            message.setMsg("修改组织时同级组织名称重复");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                        orgByPushId.setParentId(orgByParentId.getId());
                    } else {
                        Integer count = orgRepository.editOrgOrgNameByParentNull(orgName, orgByPushId.getId());
                        if (count > 0) {
                            message.setCode("303");
                            message.setMsg("修改组织时同级组织名称重复");
                            message.setData(pushId);
                            messageList.add(message);
                        }
                    }
                    orgByPushId.setEnableFlag((Integer) map.get("enableFlag"));
                    orgByPushId.setOrgAddress((String) map.get("orgAddress"));
                    orgByPushId.setOrgCode((String) map.get("orgCode"));
                    orgByPushId.setOrgLevel((Integer) map.get("orgLevel"));
                    orgByPushId.setOrgName(orgName);
                    orgByPushId.setOrgOrder((Integer) map.get("orgOrder"));
                    orgByPushId.setOrgPhone((String) map.get("orgPhone"));

                    orgRepository.save(orgByPushId);
                    log.info("***********更新组织信息  ENF****************");
                }
            } else {
                BusinessMessage message = new BusinessMessage();
                message.setCode("1003");
                message.setMsg("推送的数据为空");
                messageList.add(message);
            }
        } catch (Exception e) {
            BusinessMessage message = new BusinessMessage();
            e.printStackTrace();
            message.setCode("1002");
            message.setMsg("组织更新失败，系统异常");
            messageList.add(message);
        } finally {
            log.info("---------------调用更新组织方法 END---------------------");
            return messageList;
        }
    }

    @Override
    public List<BusinessMessage> deleteSynBaseOrg(String jsonArrayStr) {
        log.info("---------------调用删除组织方法 START ---------------------");
        List<BusinessMessage> messageList = new ArrayList<>();
        try {
            jsonArrayStr = new String(jsonArrayStr.getBytes("UTF-8"), "UTF-8");
            List<Map<String, Object>> mapList = JSONArray.parseObject(jsonArrayStr, List.class);
            if (null == mapList || mapList.size() > 0) {

                for (Map<String, Object> map : mapList) {
                    log.info("***********删除组织信息 START****************");
                    String pushId = (String) map.get("id");
                    DSysOrg orgByPushId = orgRepository.getByPushId(pushId);//当前部门信息
                    BusinessMessage message = new BusinessMessage();
                    if (orgByPushId == null) {
                        message.setCode("201");
                        message.setMsg("删除的组织不存在");
                        message.setData(pushId);
                        messageList.add(message);
                    }
                    List<DSysOrg> zijiOrgList = orgRepository.getZijiOrg(orgByPushId.getId());//查询子集部门
                    List<DSysUser> users = userRepository.getByOrgId(orgByPushId.getId());
                    if (zijiOrgList.size() > 0) {
                        message.setCode("202");
                        message.setMsg("删除的组织下存在子组织");
                        message.setData(pushId);
                        messageList.add(message);
                    } else if (users.size() > 0) {
                        message.setCode("203");
                        message.setMsg("删除的组织下存在用户");
                        message.setData(pushId);
                        messageList.add(message);
                    } else {
                        orgRepository.updateFlag(orgByPushId.getId());
                    }
                    log.info("***********删除组织信息 END****************");
                }

            } else {
                BusinessMessage message = new BusinessMessage();
                message.setCode("1003");
                message.setMsg("推送的数据为空");
                messageList.add(message);
            }
        } catch (Exception e) {
            BusinessMessage message = new BusinessMessage();
            e.printStackTrace();
            message.setCode("1002");
            message.setMsg("删除组织失败，系统异常");
            messageList.add(message);
        } finally {
            log.info("---------------调用删除组织方法 END---------------------");
            return messageList;
        }
    }
}
